import { reqGetCode, reqUserLogin, reqUserRegister, reqUserInfo, reqLogout } from '@/api/index';
import { setToken, getToken, removeToken } from '@/utils/token';

// 登录
const state = {
    code: '',
    token: getToken(),
    userinfo: {}
}
const mutations = {
    // 注册
    GETCODE(state, code) {
        state.code = code
    },
    // token数据
    USERLOGIN(state, token) {
        state.token = token
    },
    // 修改用户数据
    GETUSERINFO(state, userinfo) {
        state.userinfo = userinfo
    },
    // 退出登录清除仓库数据和本地存储数据
    CLEAROUT(state) {
        state.token = '';
        state.userinfo = {};
        removeToken();

    }
}
const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        let res = await reqGetCode(phone)

        if (res.code == 200) {
            commit('GETCODE', res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 注册
    async getUserRegister({ commit }, user) {
        let res = await reqUserRegister(user)

        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 登录
    async userLogin({ commit }, data) {
        let res = await reqUserLogin(data)
            // 服务器下发token，用户唯一标识（uuid
            // 将来经常用于带着token找服务器要用户数据进行展示
        if (res.code == 200) {
            // 用户以及获取的了token登录成功
            commit('USERLOGIN', res.data.token)
                // 还需要持久化存储token
                // localStorage.setItem('TOKEN', res.data.token)
            setToken(res.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        // 提交用户信息‘
        let res = await reqUserInfo()
        if (res.code == 200) {
            commit('GETUSERINFO', res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async userLogout({ commit }) {
        // 只是向服务器发起请求清除服务器数据
        // actions不能修改本地数据
        let res = await reqLogout()
        if (res.code == 200) {
            commit('CLEAROUT')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}